package com.training.admin.web.controller.project;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.training.admin.dao.ProjectTraineeDao;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.project.TrainingResult;
import com.training.admin.service.ProjectPhaseService;
import com.training.admin.service.ProjectResultService;
import com.training.admin.service.ProjectTraineeResultService;

/**
 * 
 * @author sjh
 *
 */
@Controller
@RequestMapping("/project-results")
@MenuSetting("menu-training-project")
public class ProjectTraineeResultController {
	
	private static final Logger logger = LoggerFactory.getLogger(ProjectTraineeResultController.class);


	@Dao
	private ProjectTraineeDao projectTraineeDao;

	@Autowired
	private ProjectResultService projectResultService;
	
	@Autowired
	private ProjectTraineeResultService projectTraineeResultService;
	
	@Autowired
	private ProjectPhaseService projectPhaseService;

	/**
	 * 考勤录入
	 * 
	 * @param prjectPhase
	 * @return
	 */
	@RequestMapping(value = "/{projectPhaseId}/attendance-upload", method = RequestMethod.GET)
	public ModelAndView attendanceUpload(@PathVariable("projectPhaseId") Long projectPhaseId) {

		ModelAndView modelAndView = new ModelAndView("project-result/project-result-trainee-attendance-upload");
		
		ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
		modelAndView.addObject("projectId", projectPhase.getProject().getId());

		modelAndView.addObject("projectPhaseId", projectPhaseId);
		return modelAndView;

	}

	/**
	 * 考勤录入
	 * 
	 * @param prjectPhaseId
	 * @param file
	 * @param attributes
	 * @return
	 */
	@RequestMapping(value = "/{projectPhaseId}/attendance-upload", method = RequestMethod.POST)
	public ModelAndView onAttendanceUpload(@PathVariable("projectPhaseId") Long projectPhaseId, @RequestParam("file") MultipartFile file,
			RedirectAttributes attributes) {
	    
	    ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
	    
	    try {
	        

	        ModelAndView modelAndView = new ModelAndView("redirect:/project-results/" + projectPhase.getProject().getId());

	        projectResultService.createByFile(file, projectPhaseId);

	        return modelAndView;
	    } catch (BusinessException e) {
	        logger.error("onAttendanceUpload error", e);
	        ModelAndView modelAndView = new ModelAndView("redirect:/project-results/" + projectPhase.getProject().getId() + "?attendanceMessage="+e.getMessage());
            return modelAndView;
	    } catch (Exception e) {
	        logger.error("onAttendanceUpload error", e);
            ModelAndView modelAndView = new ModelAndView("redirect:/project-results/" + projectPhase.getProject().getId() + "?attendanceMessage=考情录入发生异常");
            return modelAndView;
            
        }

	}

	/**
	 * 成绩录入
	 * 
	 * @param projectPhaseId
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/{projectPhaseId}/trainee-score-list", method = RequestMethod.GET)
	@MenuSetting("submenu-project-result-management")
	public ModelAndView inputResult(@PathVariable("projectPhaseId") Long projectPhaseId, Page page) {
		ModelAndView modelAndView = new ModelAndView("project-result/project-result-score-trainee-edit");
		/*
		 * ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class,
		 * projectPhaseId);
		 * 
		 * List<ProjectTrainee> projectTraineeList =
		 * projectTraineeService.listByProjectId(projectPhase.getProject().getId());
		 * 
		 * List<TrainingResult> trainingResultList =
		 * trainingResultService.listByProjectPhaseId(projectPhaseId);
		 * 
		 * Map<Long, TrainingResult> resultMap = new HashMap<Long, TrainingResult>();
		 * 
		 * for (int i = 0; i < trainingResultList.size(); i++) {
		 * 
		 * if (trainingResultList.get(i) != null) {
		 * 
		 * resultMap.put(trainingResultList.get(i).getTrainee().getId(),
		 * trainingResultList.get(i)); }
		 * 
		 * }
		 * 
		 * modelAndView.addObject("projectPhase", projectPhase);
		 * modelAndView.addObject("currentPhase", projectPhase.getPhase());
		 * modelAndView.addObject("projectTrainees", projectTraineeList);
		 * modelAndView.addObject("trainingResults", resultMap);
		 */
		modelAndView.addObject("projectPhaseId", projectPhaseId);
		return modelAndView;
	}
	
	/**
	 * 培训结果提交
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{projectPhaseId}/trainee-score-list", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-result-management")
	@ResponseBody
	public HttpResult onInputResult(@PathVariable("projectPhaseId") Long projectPhaseId,@RequestParam(value = "userId") Long userId,@RequestParam(value = "score") Float score,@RequestParam(value = "comment") String comment,@RequestParam(value ="absence") Float absence,@RequestParam(value = "resit") Boolean resit) {

		HttpResult httpResult = new HttpResult();
		try {
			projectResultService.inputResult(projectPhaseId, userId, score, comment, absence, resit);
			httpResult.success().message("项目结果录入成功");

		} catch (Exception e) {
			httpResult.fail("500").message("项目结果录入失败! " + e.getMessage());
			logger.error("#onInputResult() - create project fail, exception is [{}]", e);
		}

		return httpResult;

	}

	/**
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "/select-search", params = "query", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public @ResponseBody HttpResult selectSearch(@RequestParam("query") String q, @RequestParam("projectPhaseId") Long projectPhaseId) {
		HttpResult httpResult = new HttpResult();

		List<Map<String, String>> maps = projectTraineeResultService.listProjectTrainee(q, projectPhaseId);
		httpResult.success().data("projectTrainees", maps);
		
		return httpResult;
	}
	/**
	 * 
	 * @param userId
	 * @param projectPhaseId
	 * @return
	 */
	
	  @RequestMapping(value = "/select", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) 
	  @ResponseBody
	  public HttpResult select(@RequestParam("userId") Long userId, @RequestParam("projectPhaseId") Long projectPhaseId) {
		 
		  HttpResult httpResult = new HttpResult();
	  
	  TrainingResult trainingResult = projectTraineeResultService.loadByTraineeId(userId, projectPhaseId);
	  Map<String, Object> trainingResultMap = new HashMap<String, Object>();
	  trainingResultMap.put("score", trainingResult.getScore());
	  trainingResultMap.put("absence", trainingResult.getAbsence());
	  trainingResultMap.put("resit", trainingResult.isResit());
	  trainingResultMap.put("comment", trainingResult.getComment());
	  httpResult.success().data("trainingResult", trainingResultMap);
	  return httpResult; 
	  }

}
